import {Checkbox, Dialog, Form, Input, Toast} from "antd-mobile";
import {useState} from "react";
import {userController} from "./http/UserController";

interface LoginDialogProps {
    visible: boolean,
    success?: (user: any) => void,
    fail?: (res: any) => void,
    onClose: ()=>void
}
const LoginDialog = (props: LoginDialogProps) => {
    const [form] = Form.useForm();
    const [account, setAccount] = useState<string>("");
    const [password, setPassword] = useState<string>("");

    const onOkClick = ()=>{
        userController.login(account, password).then(res=>{
            if (props.success)
                props.success(res);
            props.onClose();
        }).catch(err=>{
            Toast.show({content: "登录失败：账号或密码错误"});
            if (props.fail)props.fail("失败");
            props.onClose();
        });

    }

    return (
        <Dialog visible={props.visible}
                closeOnAction
                actions={[
                    [{
                        key: "login",
                        text: "登录",
                        onClick: onOkClick
                    },
                    {
                        key: "cancel",
                        text: "取消",
                        onClick: ()=>{if(props.fail)props.fail("取消");props.onClose();}
                    }]
                ]}
                content={
                    <Form form={form} layout={"horizontal"} style={{borderStyle: "none"}}>
                        <Form.Item name={"account"}
                                   label={"账号"}>
                            <Input value={account} onChange={setAccount} />
                        </Form.Item>
                        <Form.Item name={"password"}
                                   label={"密码"}>
                            <Input value={password} onChange={setPassword} type={"password"}/>
                        </Form.Item>
                        <Form.Item name={"remember"}>
                            <Checkbox value={"true"}>记住我</Checkbox>
                        </Form.Item>
                    </Form>
                }
                title={<h2>登录</h2>}
        >
        </Dialog>

    );
}

export default LoginDialog;
